/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: client.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月14日 星期3 16时18分54秒
***************************************************/
// 开发一个计算服务器，能够计算两个整数的加减乘除
//          ##add#23#12##

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "cJSON.h"
struct data
{
	int type;
	char count[10];
	float num1;
	float num2;
};

struct number
{
	float sum;
};

int main(int argc,const char* argv[])
{
	int sock = 0;
	int ret = 0;
	char *buf = NULL;
	char dest[20] = {0};
	
	
	// 初始化结构体变量用于保存服务器地址和信息
	struct sockaddr_in serAddr;
	memset(&serAddr,0,sizeof(serAddr));

	// 创建UDP套接字 UDP标识  传输模式(报文传输)
	sock = socket(AF_INET,SOCK_DGRAM,0);
	if(sock == -1) {
		perror("socket");
		exit(-1);
	}

	// 设置地址族
	serAddr.sin_family = AF_INET;
	// 设置端口号
	serAddr.sin_port = htons(6666);
	// 设置ip
	serAddr.sin_addr.s_addr = inet_addr("192.168.198.128");

	struct data dat;
	memset(&dat,0,sizeof(dat));
	
	struct number num;
	memset(&num,0,sizeof(num));

	cJSON *json = NULL;

	while(1){
	
		printf("1------- 加\n");
		printf("2------- 减\n");
		printf("3------- 乘\n");
		printf("4------- 除\n");
		printf("0------- 退出\n");
		printf("你想进行什么操作:\n");
		scanf("%d",&dat.type);
		if(dat.type == 0){
			break;
		}
		if(dat.type == 1){
			strcpy(dat.count,"add");
		}
		if(dat.type == 2){
			strcpy(dat.count,"minus");
		}
		if(dat.type == 3){
			strcpy(dat.count,"multiply");
		}
		if(dat.type == 4){
			strcpy(dat.count,"divide");
		}
		printf("请输入数字1:\n");
		scanf("%f",&dat.num1);
		printf("请输入数字2:\n");
		scanf("%f",&dat.num2);

		
		json = cJSON_CreateObject();


		
		cJSON_AddItemToObject(json,"type",cJSON_CreateNumber(dat.type));
		cJSON_AddItemToObject(json,"count",cJSON_CreateString(dat.count));
		cJSON_AddItemToObject(json,"num1",cJSON_CreateNumber(dat.num1));
		cJSON_AddItemToObject(json,"num2",cJSON_CreateNumber(dat.num2));
	
		buf = cJSON_Print(json);	
	
    		ret = sendto(sock,buf,strlen(buf),0,(struct sockaddr *)&serAddr,sizeof(struct sockaddr));
		if(ret == -1)
		{
			perror("sendto");
		}




		ret = recvfrom(sock,dest,sizeof(dest),0,NULL,NULL);
		if(ret == -1){
			perror("recvfrom");
			exit(-1);
		}
		
		json = cJSON_Parse(dest);
		cJSON *node = NULL;

		node = cJSON_GetObjectItem(json,"sum");
		if(node == NULL)
		{
			printf("can't find\n");
			exit(-1);
		}
		if(node->type == cJSON_Number)
		{
			num.sum = node->valuedouble;
		}
		
	
		printf("number = %.2f\n",num.sum);

		cJSON_Delete(json);
		}

		
	//关闭套接字 
	close(sock);
    return 0;
}

